﻿using System;
using System.Web;
using log4net;

namespace JQuery.WebKit.Common.Logging
{
    public enum LogMessageType
    { 
        Info,
        Warn,
        Error
    }

    public static class LogManager
    {
        private static ILog _log;
        
        public static void RegisterLogger(string loggerName)
        {
            _log = log4net.LogManager.GetLogger(loggerName);
        }

        public static void LogInfoFormat(string format, params object[] args)
        {
            LogMessageFormat(LogMessageType.Info, format, args);
        }

        public static void LogInfo(string message)
        {
            LogMessage(LogMessageType.Info, message);
        }

        public static void LogErrorFormat(string format, params object[] args)
        {
            LogMessageFormat(LogMessageType.Error, format, args);
        }

        public static void LogError(string message)
        {
            LogMessage(LogMessageType.Error, message);
        }

        public static void LogError(Exception error)
        {
            LogMessageFormat(LogMessageType.Error, "{0}", error);
        }

        public static void LogWarnFormat(string format, params object[] args)
        {
            LogMessageFormat(LogMessageType.Warn, format, args);
        }

        public static void LogWarn(string message)
        {
            LogMessage(LogMessageType.Warn, message);
        }

        public static void LogMessage(LogMessageType messageType, string message)
        {
            LogMessageFormat(messageType, message);
        }

        public static void LogMessageFormat(LogMessageType messageType, string format, params object[] args)
        {
            if (_log == null)
            {
                return;
            }

            switch (messageType)
            {
                case LogMessageType.Info:
                    _log.InfoFormat("[sid: {0}] {1}", GetSessionId(), string.Format(format, args));
                    break;
                case LogMessageType.Warn:
                    _log.WarnFormat("[sid: {0}] {1}", GetSessionId(), string.Format(format, args));
                    break;
                case LogMessageType.Error:
                    _log.ErrorFormat("[sid: {0}] {1}", GetSessionId(), string.Format(format, args));
                    break;
                default:
                    break;
            }
        }

        private static string GetSessionId()
        {
            string sessionId;
            if (HttpContext.Current != null &&
                HttpContext.Current.Session != null)
            {
                sessionId = HttpContext.Current.Session.SessionID;
            }
            else
            {
                sessionId = "n/a";
            }
            return sessionId;
        }
    }
}
